package server.mapper;


import java.io.InputStream;
import java.net.Socket;
import java.net.URI;
import java.util.Map;

/**
 * @ClassName: RequestProcessor
 * @Description: 请求执行器
 * @Author: wuguizhen
 * @Date: 2020/3/31 16:11
 * @Version: v1.0 文件初始创建
 */
public class RequestProcessor extends Thread {

    private Socket socket;
    private Server server;

    public RequestProcessor(Socket socket, Server server) {
        this.socket = socket;
        this.server = server;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            System.out.println(request.getUrl());
            //访问地址 http://127.0.0.1:8080/a/b/c
            // /a/b/c
            String url = request.getUrl();
            /** 解析url 第一个位置 拿到项目名称 */
            String contextName = url.split("/")[1];
            /** 获取项目映射 */
            Map<String,Context> contextMap = server.getMapper().getHost().getContextMap();
            /** 没有匹配的应用返回404 */
            if(!contextMap.containsKey(contextName)){
                response.output(HttpProtocolUtil.getHttpHeader404());
            }else{
                /** 获取该应用的映射关系 */
                Context context = contextMap.get(contextName);
                /** 获取去掉项目路径后的路径 */
                String mapping = url.substring(url.indexOf(contextName)+contextName.length(),url.length());
                Warpper wrapper = context.getWarpper();
                /** 解析静态资源 */
                if(mapping.contains(".html")){
                    Map<String, URI> map = wrapper.getMapUri();
                    if(map.containsKey(mapping)){
                        response.outputHtml(map.get(mapping));
                    }else{
                        response.output(HttpProtocolUtil.getHttpHeader404());
                    }
                }else{
                    /** 解析动态资源 */
                    Map<String, HttpServlet> map = wrapper.getServletMap();
                    if(map.containsKey(mapping)){
                        HttpServlet httpServlet = map.get(mapping);
                        httpServlet.service(request, response);
                    }else{
                        response.output(HttpProtocolUtil.getHttpHeader404());
                    }
                }
            }
            socket.close();
        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
